package com.chengww.grab_rp.api

import com.chengww.grab_rp.utils.MD5
import java.util.*

/**
 * Created by chengww on 2/20/21
 * @author chengww
 */
class RequestBody {

    private val body: MutableMap<String, String> = TreeMap(MapKeyComparator())
    private var requestBody: String? = null

    fun put(key: String, value: String): RequestBody {
        body[key] = value
        return this
    }

    fun sign(md5Key: String): Map<String, String> {
        if (requestBody.isNullOrEmpty()) {
            requestBody = this.signInternal(md5Key)
        }
        return put("sign", requestBody ?: "").body
    }

    private fun generateSign(md5Key: String): String {
        val requestBody = StringBuilder()
        for (key in body.keys) {
            requestBody.append(key).append("=").append(body[key]).append("&")
        }
        if (requestBody.isNotEmpty()) {
            requestBody.deleteCharAt(requestBody.length - 1)
        }
        val value = requestBody.append("&key=").append(md5Key).toString()
        return MD5.digest(value).toUpperCase(Locale.ROOT)
    }

    private fun signInternal(md5Key: String): String {
        return try {
            generateSign(md5Key)
        } catch (e: Exception) {
            ""
        }
    }
}

class MapKeyComparator : Comparator<String?> {

    override fun compare(o1: String?, o2: String?): Int {
        if (o1 == null) {
            return if (o2 == null) 0 else 1
        } else if (o2 == null) {
            return -1
        }
        return o1.compareTo(o2)
    }
}